package simulator;
import java.util.*;
import java.net.URL;
import java.io.*;

/**
 * Factory for creating Robots with different configurations of sensors.
 */
public class RobotFactory {
  public static Robot getDefaultConfiguration(Environment env) {
    Robot robot = new Robot();
    //TODO place new servos and locs
    robot.addSensor(new BumpSensor(env, 5.0, 0.0)); //TODO use dual bump sensor
    //CENTER RF 
    robot.addSensor(new RangeFinder(env, 0, 0.0, 150, 0));
    //RIGHT RF, on Servo
    robot.addSensor(new RangeFinder(env, 0, 0, 150, 0)); 
    RangeFinder[] r= {robot.getRangeFinders()[robot.getRangeFinders().length-1]};
    robot.addSensor(new Servo(env, r, 45));
    //RIGHT RF, on Servo
    robot.addSensor(new RangeFinder(env, 0, 0, 150, 0)); 
    RangeFinder[] r1= {robot.getRangeFinders()[robot.getRangeFinders().length-1]};
    robot.addSensor(new Servo(env, r1, -45));

    /*robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, 45)); 
    robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, -45)); 
    robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, 180+45)); 
    robot.addSensor(new RangeFinder(env, 0.0, 0.0, 100, 180-45)); */
    robot.addSensor(new BeaconSensor(env, 0.0, 0.0));
    robot.addSensor(new Compass(env));
    //robot.setServo(new Servo(robot.getRangeFinders()));*/
    return robot;
  }
  
  /**
   * Download configuration via URL
   */
  public static Robot loadConfiguration(Environment env, URL url)
      throws IOException {
    Robot robot = new Robot();
    BufferedReader in = new BufferedReader(
        new InputStreamReader((InputStream)url.getContent()));
        
    String line = "";
    while((line = in.readLine()) != null) {
      StringTokenizer st = new StringTokenizer(line, " ");
      if(st.countTokens() > 1) {
        String type = st.nextToken();
        if(type.equals("BeaconSensor")) {
          robot.addSensor(new BumpSensor(env,
                                          Double.parseDouble(st.nextToken()),
                                          Double.parseDouble(st.nextToken())));
        }
        if(type.equals("TouchSensor")) {
          robot.addSensor(new BumpSensor(env,
                                          Double.parseDouble(st.nextToken()),
                                          Double.parseDouble(st.nextToken())));
        }
        if(type.equals("RangeFinder")) {
          robot.addSensor(new RangeFinder(env,
                                          Double.parseDouble(st.nextToken()),
                                          Double.parseDouble(st.nextToken()),
                                          Integer.parseInt(st.nextToken()),
                                          Integer.parseInt(st.nextToken())));
        }
      }
    }
    return robot;
  }

}